package com.example.denglu.service;

import com.example.denglu.util.DBUtil;
import com.example.denglu.util.MD5Util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;

import javax.servlet.http.HttpSession;

public class UserService {
    
    public static boolean registerUserByPhone(String phone, String username, String password) {
        String sql = "INSERT INTO users (phone, username, password) VALUES (?, ?, ?)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            
            ps.setString(1, phone);
            ps.setString(2, username);
            ps.setString(3, MD5Util.encrypt(password));
            return ps.executeUpdate() > 0;
            
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static boolean verifyUser(String phone, String password) {
        String sql = "SELECT password FROM users WHERE phone = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            
            ps.setString(1, phone);
            ResultSet rs = ps.executeQuery();
            
            if (rs.next()) {
                String storedPassword = rs.getString("password");
                return storedPassword.equals(MD5Util.encrypt(password));
            }
            return false;
            
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static boolean registerByUsername(String username, String password) {
        String sql = "INSERT INTO users (username, password) VALUES (?, ?)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            
            ps.setString(1, username);
            ps.setString(2, MD5Util.encrypt(password));
            return ps.executeUpdate() > 0;
            
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static boolean loginByUsername(String username, String password) {
        String sql = "SELECT password FROM users WHERE username = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            
            ps.setString(1, username);
            ResultSet rs = ps.executeQuery();
            
            if (rs.next()) {
                String storedPassword = rs.getString("password");
                return storedPassword.equals(MD5Util.encrypt(password));
            }
            return false;
            
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static boolean loginByPhone(String phone, String code, HttpSession session) {
        String savedCode = (String) session.getAttribute(phone + "_code");
        System.out.println("验证码登录 - 手机号：" + phone);
        System.out.println("验证码登录 - 用户输入：" + code);
        System.out.println("验证码登录 - 存储的值：" + savedCode);
        
        if (savedCode == null) {
            return false; // 验证码过期
        }
        
        if (!savedCode.equals(code)) {
            return false; // 验证码错误
        }
        
        // 验证成功后清除验证码
        session.removeAttribute(phone + "_code");
        session.removeAttribute(phone + "_lastSendTime");
        
        return true;
    }

    public static boolean resetPassword(String phone, String newPassword, String code, HttpSession session) {
        // 验证验证码
        String savedCode = (String) session.getAttribute(phone + "_code");
        if (savedCode == null || !savedCode.equals(code)) {
            return false;
        }
        
        // 检查手机号是否已注册
        String username = getRegisteredUsername(phone);
        if (username == null) {
            return false; // 手机号未注册
        }
        
        // 更新密码
        String sql = "UPDATE users SET password = ? WHERE phone = ? AND username = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            
            ps.setString(1, MD5Util.encrypt(newPassword));
            ps.setString(2, phone);
            ps.setString(3, username);
            
            boolean success = ps.executeUpdate() > 0;
            if (success) {
                session.removeAttribute(phone + "_code"); // 重置成功后清除验证码
            }
            return success;
            
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 检查手机号是否已注册
    public static boolean isPhoneRegistered(String phone) {
        String sql = "SELECT id FROM users WHERE phone = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, phone);
            ResultSet rs = ps.executeQuery();
            return rs.next();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 使用手机号创建临时用户（密码为空）
    public static boolean createTempUser(String phone) {
        String sql = "INSERT INTO users (phone, username) VALUES (?, ?)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, phone);
            ps.setString(2, phone); // 默认使用手机号作为用户名
            return ps.executeUpdate() > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 设置用户密码
    public static boolean setPassword(String phone, String password) {
        String sql = "UPDATE users SET password = ? WHERE phone = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, MD5Util.encrypt(password));
            ps.setString(2, phone);
            return ps.executeUpdate() > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 检查用户是否需要设置密码
    public static boolean needSetPassword(String openid) {
        String sql = "SELECT u.password FROM users u " +
                     "JOIN user_wechat w ON u.id = w.user_id " +
                     "WHERE w.openid = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, openid);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                String password = rs.getString("password");
                System.out.println("检查用户密码状态，openid: " + openid + ", password: " + (password == null ? "null" : "非空"));
                return password == null || password.trim().isEmpty();
            }
            System.out.println("未找到用户，openid: " + openid);
            return false;
        } catch (Exception e) {
            System.out.println("检查密码状态失败: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    public static boolean createOrUpdateWeChatUser(String openid, String nickname, String headimgurl, String phone) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        
        try {
            conn = DBUtil.getConnection();
            System.out.println("开始创建微信用户，openid: " + openid);
            
            conn.setAutoCommit(false);
            
            // 检查是否已存在微信用户
            String checkSql = "SELECT user_id FROM user_wechat WHERE openid = ?";
            ps = conn.prepareStatement(checkSql);
            ps.setString(1, openid);
            rs = ps.executeQuery();
            
            if (!rs.next()) {
                System.out.println("未找到现有用户，创建新用户");
                // 创建新用户，使用手机号或昵称或openid作为用户名
                String createUserSql = "INSERT INTO users (username, phone, password) VALUES (?, ?, NULL)";
                ps = conn.prepareStatement(createUserSql, Statement.RETURN_GENERATED_KEYS);
                
                // 按优先级选择用户名：手机号 > 昵称 > openid
                String username;
                if (phone != null && !phone.trim().isEmpty()) {
                    username = phone;
                } else if (nickname != null && !nickname.trim().isEmpty()) {
                    username = nickname;
                } else {
                    username = "wx_" + openid.substring(0, 8);
                }
                
                ps.setString(1, username);
                ps.setString(2, phone);
                ps.executeUpdate();
                
                rs = ps.getGeneratedKeys();
                if (rs.next()) {
                    long userId = rs.getLong(1);
                    System.out.println("创建用户成功，userId: " + userId);
                    
                    // 关联微信信息
                    String createWeChatSql = "INSERT INTO user_wechat (user_id, openid, nickname, headimgurl) VALUES (?, ?, ?, ?)";
                    ps = conn.prepareStatement(createWeChatSql);
                    ps.setLong(1, userId);
                    ps.setString(2, openid);
                    ps.setString(3, nickname);
                    ps.setString(4, headimgurl);
                    ps.executeUpdate();
                    System.out.println("关联微信信息成功");
                }
            } else {
                // 如果用户已存在且有新的手机号，更新手机号和用户名
                if (phone != null && !phone.trim().isEmpty()) {
                    long userId = rs.getLong("user_id");
                    String updatePhoneSql = "UPDATE users SET phone = ?, username = ? WHERE id = ?";
                    ps = conn.prepareStatement(updatePhoneSql);
                    ps.setString(1, phone);
                    ps.setString(2, phone); // 使用手机号作为新的用户名
                    ps.setLong(3, userId);
                    ps.executeUpdate();
                    System.out.println("更新用户手机号和用户名成功");
                }
            }
            
            conn.commit();
            return true;
        } catch (Exception e) {
            System.out.println("创建微信用户失败: " + e.getMessage());
            e.printStackTrace();
            try {
                if (conn != null) conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            return false;
        } finally {
            try {
                if (rs != null) rs.close();
                if (ps != null) ps.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static boolean setWeChatUserPassword(String openid, String password) {
        String sql = "UPDATE users u " +
                     "JOIN user_wechat w ON u.id = w.user_id " +
                     "SET u.password = ? " +
                     "WHERE w.openid = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            
            ps.setString(1, MD5Util.encrypt(password));
            ps.setString(2, openid);
            
            System.out.println("设置微信用户密码 - openid: " + openid);
            boolean success = ps.executeUpdate() > 0;
            System.out.println("设置密码结果: " + success);
            
            return success;
        } catch (Exception e) {
            System.out.println("设置密码失败: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    public static boolean updateWeChatUserPhone(String openid, String phone) {
        String sql = "UPDATE users u " +
                     "JOIN user_wechat w ON u.id = w.user_id " +
                     "SET u.phone = ?, u.username = ? " +
                     "WHERE w.openid = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            
            ps.setString(1, phone);
            ps.setString(2, phone); // 使用手机号作为用户名
            ps.setString(3, openid);
            
            System.out.println("更新微信用户手机号和用户名 - openid: " + openid + ", phone: " + phone);
            boolean success = ps.executeUpdate() > 0;
            System.out.println("更新结果: " + success);
            
            return success;
        } catch (Exception e) {
            System.out.println("更新手机号失败: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    public static boolean checkUserHasPhone(String openid) {
        String sql = "SELECT u.phone FROM users u " +
                     "JOIN user_wechat w ON u.id = w.user_id " +
                     "WHERE w.openid = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            
            ps.setString(1, openid);
            ResultSet rs = ps.executeQuery();
            
            if (rs.next()) {
                String phone = rs.getString("phone");
                return phone != null && !phone.trim().isEmpty();
            }
            return false;
        } catch (Exception e) {
            System.out.println("检查用户手机号失败: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    // 修改 isPhoneRegistered 方法，增加返回用户名功能
    public static String getRegisteredUsername(String phone) {
        String sql = "SELECT username FROM users WHERE phone = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, phone);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                return rs.getString("username");
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
} 